/*
 * TcpTest.cpp
 *
 *  Created on: Dec 31, 2013
 *      Author: slava
 */

#include <iostream>
#include "cm_net.h"
#include <fstream>
#include <sstream>
#include <cstdlib>

using std::cout;
using std::cin;
using std::endl;
using std::fstream;
using std::istringstream;
int run_client() {
	cout << "Setting up client" << endl;
	UdpClient client("localhost");
	cout << "Client is up and connected" << endl;
	cout << "Sending to server" << endl;
	client.send("hello");
	cout << "Waiting for response from server" << endl;
	string res = client.receive();
	if (res != string("bye")) {
		cout << "error. wanted \"bye\", received " << res << endl;
		std::exit(1);
	}
	cout << "received: " << res << endl;
	cout << "server responded" << endl;
	return 0;
}

int run_server() {
	cout << "Setting up server" << endl;
	UdpServer server;
	cout << "Server is up and connected" << endl;
	cout << "Waiting for client" << endl;
	string res = server.receive();
	if (res != string("hello") && res != string("hello\n")) {
		cout << "error. wanted \"hello\", received " << res << endl;
		std::exit(1);
	}
	cout << "Server received: " << res << endl;
	cout << "Sending to client" << endl;
	if (!server.last_addr_p) {
		cout << "Error: last addres is null." << endl;
		return 1;
	}
	server.last_addr_p->send("bye");
	cout << "Server sent bye" << endl;
	return 0;
}

int main(int argc, char* argv[]) {
	try {
		//run_client();
//		if (pid_t pid = fork()) {
//			wait();
//		} else {
			run_server();
//		}
	} catch (ConnectionError& e) {
		cout << "error: " << e.what << endl;
		cout << "Terminating client" << endl;
	}
	return 0;
}
